<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose showFooter :title="getTitle" :width="drawerWith" @ok="handleSubmit">
    <BasicForm @register="registerForm"> </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/form';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import { formSchema } from './data';
import { add, update } from './api';
import { useAppInject } from '@apps/antd-admin/src/hooks/web/use-app-inject';
export default defineComponent({
  name: 'serverDrawer',
  components: { BasicDrawer, BasicForm },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const isUpdate = ref(true);

    const { getIsMobile } = useAppInject();
    const drawerWith = ref('40%');
    if (unref(getIsMobile)) {
      drawerWith.value = '80%';
    }

    const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
      labelWidth: 155,
      labelCol: { span: 6 },
      schemas: formSchema,
      showActionButtonGroup: false,
    });

    const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async data => {
      resetFields();
      setDrawerProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;

      if (unref(isUpdate)) {
        setFieldsValue({
          ...data.record,
        });
      }
    });

    const getTitle = computed(() => (!unref(isUpdate) ? '新增卡权益' : '编辑卡权益'));

    async function handleSubmit() {
      try {
        const values = await validate();
        setDrawerProps({ confirmLoading: true });
        if (unref(isUpdate)) {
          await update(values);
        } else {
          await add(values);
        }
        console.log(values);
        closeDrawer();
        emit('success', false);
      } finally {
        setDrawerProps({ confirmLoading: false });
      }
    }

    return {
      registerDrawer,
      registerForm,
      getTitle,
      handleSubmit,
      drawerWith,
    };
  },
});
</script>
